package com.hy.item.service;

import com.hy.common.enums.ExceptionEnums;
import com.hy.common.exception.XkException;
import com.hy.item.mapper.SpecGroupMapper;
import com.hy.item.mapper.SpecParamMapper;
import com.hy.item.pojo.SpecGroup;
import com.hy.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SpecificationService {
    /**
     * 通过分类id查询规格参数
     * @param cid
     * @return
     */
    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroup> queryGroupByCid(Long cid) {
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(cid);
        List<SpecGroup> list = specGroupMapper.select(specGroup);
        if (CollectionUtils.isEmpty(list)){
            throw new XkException(ExceptionEnums.CATEGORY_NOT_FOUND);
        }
        return list;
    }
    /**
     * 根据参数查询规格参数
     * @param gid
     * @return
     */
    public List<SpecParam> queryParamList(Long gid, Long cid, Boolean searching) {
        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);

        List<SpecParam> list = specParamMapper.select(specParam);
        if (CollectionUtils.isEmpty(list)){
            throw new XkException(ExceptionEnums.CATEGORY_NOT_FOUND);
        }
        return list;
    }

    /**
     * 根据分类id查询规格组及规格参数
     * @param cid
     * @return
     */
    public List<SpecGroup> queryListByCid(Long cid) {
        //查询规格组
        List<SpecGroup> groups = queryGroupByCid(cid);
        //查询当前分类下的所有的规格参数
        List<SpecParam> specParams = queryParamList(null, cid, null);
        //方法一将数据封装到group中，可以使用双重for,这种做法比较麻烦
        //方法二，先把规格参数变成map,map的key是规格组id,值是此id下的所有的规格参数
        Map<Long,List<SpecParam>> map=new HashMap<>();
        for (SpecParam param:specParams){
            if (!map.containsKey(param.getGroupId())){
                //这个组id在map中不存在，新建一个List集合
                map.put(param.getGroupId(),new ArrayList<>());
            }
            //存不存在都将param保存到list集合中
            List<SpecParam> list = map.get(param.getGroupId());//先拿到list
            //将param放到list中
            list.add(param);
        }
        for (SpecGroup group:groups){
            group.setParams(map.get(group.getId()));//通过key得到value
        }
        return groups;
    }
}
